<template>
    <div ref="vcontainerRef" class="video-container" v-loading="loading" @click="click" @dblclick="dblclick"
        @mousemove="mousemove" element-loading-background="#0000007a" @fullscreenchange="fullHandler">
        <video ref="playerRef" :style="{ zIndex: videoZIndex,transform:isDesktop?'':'scaleX(-1)' }" @contextmenu.prevent="() => { }" @play="playerHandler"
            @pause="stopHandler" @ended="stopHandler">
            您的浏览器不支持 video 标签
        </video>
        <span style="display: flex;position: absolute; top: 10px; left: 10px;color: rgba(101, 100, 100, 0.653);">{{
            props.user }}</span>
        <div :style="{ zIndex: videoZIndex + 1, opacity: controlOpacity }" @click.stop class="video-control">
            <div class="control-left" @click.stop>
                <el-icon class="control-button" size="32" color="white" @click="click">
                    <VideoPlay v-show="isPlayer" />
                    <VideoPause v-show="!isPlayer" />
                </el-icon>
            </div>

            <div class="control-right" @click.stop>
                <div style="display: flex;" @mouseleave="hiddnVolume" @mouseenter="showVolume">
                    <el-icon class="mute-control" size="32" color="white" @click.stop="mutedChange">
                        <Microphone v-show="!playerConfig.muted && volume > 0" />
                        <Mute v-show="playerConfig.muted || volume === 0" />
                    </el-icon>
                    <el-slider :style="{ display: volumeDisplay }" ref="volumeControlRef" vertical height="75px"
                        size="small" class="volume-controls" v-model="volume" />
                </div>
                <el-icon @click="fullscreen" color="white" size="32">
                    <Fullscreen v-show="!fullScreenState" />
                    <ShrinkScreen v-show="fullScreenState" />
                </el-icon>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, watch, type PropType } from 'vue';
import Fullscreen from './icons/FullScreen.vue';
import Microphone from './icons/Microphone.vue';
import Mute from './icons/Mute.vue';
import ShrinkScreen from './icons/ShrinkScreen.vue';
import VideoPause from './icons/VideoPause.vue';
import VideoPlay from './icons/VideoPlay.vue';
const loading = ref(false);
const videoZIndex = ref(10)
const playerRef = ref<HTMLVideoElement | undefined>();
const vcontainerRef = ref<HTMLVideoElement | undefined>();
const volume = ref(0)
const volumeControlRef = ref<HTMLElement>()
const playerConfig = reactive({
    volume: 0 as number,
    muted: false as boolean,
})
const isPlayer = ref<boolean>(false)
const fullScreenState = ref(false)

// 监听视频的 play 和 pause 事件
const bindVolume = () => {
    const player = playerRef.value;
    if (player) {
        player.muted = true;
        player.volume = 0.5;
        playerConfig.volume = player.volume;
        volume.value = player.volume * 100;
        // player.muted
        player.addEventListener('volumechange', () => {
            volume.value = player.muted ? 0 : player.volume * 100;
            playerConfig.muted = player.muted;
            if (player.volume !== 0 || Math.abs(playerConfig.volume - player.volume) < 0.2) {
                playerConfig.volume = player.volume;
            }
        });
    }
}
const playerHandler = (e: Event) => {
    isPlayer.value = true;
}
const stopHandler = (e: Event) => {
    console.log("监听到 stopHandler 停止播放");
    isPlayer.value = false;
}

const stop = () => {
    isPlayer.value = false;
    if (playerRef.value) {
        playerRef.value.pause()
        const stream = playerRef.value.srcObject;
        if (stream) {
            const tracks: MediaStreamTrack[] = (stream as MediaStream).getTracks();
            if (tracks) {
                tracks.forEach(function (track) {
                    track.stop();
                });
            }
        }
        playerRef.value.srcObject = null;
        loading.value = false;
    }
    props.stop ? props.stop() : undefined;
}

const mutedChange = () => {
    let player = playerRef.value;
    if (player) {
        player.muted = !player.muted;
        if (!player.muted) {
            volume.value = playerConfig.volume !== 0 ? playerConfig.volume * 100 : 50;
            player.volume = playerConfig.volume !== 0 ? player.volume : 0.5;
            playerConfig.volume = playerConfig.volume !== 0 ? playerConfig.volume : 0.5;
        }
    }

}
onMounted(async () => {
    await nextTick();
    bindVolume();
    fullScreenState.value = document.fullscreenElement !== null;
});
const fullHandler = (e: Event) => {
    // console.log("document.fullscreenElement",document.fullscreenElement);
    fullScreenState.value = document.fullscreenElement !== null;
}
let clickControl: number | undefined;
const dblclick = () => {
    if (clickControl) {
        clearTimeout(clickControl);
        clickControl = undefined;
    }
    fullscreen()
}
const click = () => {
    if (clickControl) {
        clearTimeout(clickControl)
        clickControl = undefined;
        return
    }
    clickControl = setTimeout(() => {
        loading.value = true;
        if (props.click) {
            props.click()
        }
        clickControl = undefined;
    }, 300);
}
const fullscreen = () => {
    if (document.fullscreenElement) {
        document.exitFullscreen();
    } else if (vcontainerRef.value?.requestFullscreen) {
        vcontainerRef.value?.requestFullscreen();
    } else if ((vcontainerRef.value as any).mozRequestFullScreen) { // Firefox
        (vcontainerRef.value as any).mozRequestFullScreen();
    } else if ((vcontainerRef.value as any).webkitRequestFullscreen) { // Chrome, Safari and Opera
        (vcontainerRef.value as any).webkitRequestFullscreen();
    }
}
/**
 * 父类传入
 */
const props = defineProps({
    click: {
        // type: Function as PropType<(p: HTMLVideoElement | undefined) => void>,
        type: Function as PropType<() => void>,
        default: undefined
    },
    play: {
        type: Function as PropType<() => void>,
        default: undefined
    },
    stop: {
        type: Function as PropType<() => void>,
        default: undefined
    },
    stream: {
        type: Object as PropType<MediaProvider | null>,
        default: null
    },
    user: {
        type: String,
        default: ''
    },
    isDesktop:{
        type: Boolean,
        default: false
    }
})
/**
 * 暴露给父类
 */
defineExpose({
    isPlayer
})
watch(() => props.stream, async (v) => {    
    if (playerRef.value) {
        loading.value = false;
        if (v) {
            playerRef.value.srcObject = v;
            await playerRef.value.play();
            props.play ? props.play() : undefined
        } else {
            stop();
        }
    }
})
// const volumeDisplay = ref('flex')
const volumeDisplay = ref('none')
let sTimer: number;
const hiddnVolume = () => {
    sTimer = setTimeout(() => {
        if (volumeControlRef.value) {
            volumeDisplay.value = 'none'
        }
        clearTimeout(sTimer)
    }, 300);
}
const showVolume = () => {
    if (volumeControlRef.value) {
        volumeDisplay.value = 'flex'
    }
    clearTimeout(sTimer)
}
const controlOpacity = ref(0)
let sCTimer: number | undefined;
const mousemove = () => {
    controlOpacity.value = 1;
    if (sCTimer) {
        clearTimeout(sCTimer);
        sCTimer = undefined
    }
    sCTimer = setTimeout(() => {
        controlOpacity.value = 0;
        clearTimeout(sCTimer);
        sCTimer = undefined
    }, 200);
}
</script>

<style scoped>
.video-container {
    position: relative;
    /* color: rgba(101, 100, 100, 0.653); */
    /* border: 1px solid black; */
}

.video-container video {
    display: flex;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-control {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 5px 10px 5px 10px;
    display: flex;
    background: rgba(0, 0, 0, 0.2);
    justify-content: space-between;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;

}

.volume-controls {
    position: absolute;
    bottom: 46px;
    height: 100px;
    background-color: rgba(0, 0, 0, 0.676);
    --el-slider-height: 3px;
    --el-slider-button-size: 12px;
    --el-slider-button-wrapper-offset: -16px;
}

.control-left {
    /* width: 60px; */
    display: flex;
    margin-left: 10px;
    justify-content: center;
    align-items: center;

}

.control-right {
    /* width: 180px; */
    display: flex;
    /* justify-content: center; */
    justify-content: space-between;
    align-items: center;
}

.control-right>* {
    margin-right: 10px;
}
</style>